﻿Public Class MTrk
    Inherits List(Of MidiEvent)

    Private Sub New()
        MyBase.New()
    End Sub

    Public Shared Function FromStream(InputReader As BigEndianBinaryReader) As MTrk

        Dim ChunkID As String = InputReader.Read4CharString
        If ChunkID <> "MTrk" Then _
            Throw New MidiFileFormatException(InputReader.Position - 4, "Unexpected chunk ID """ & ChunkID & """")

        Dim Result As New MTrk
        Dim ExceptionOffsetPosition As Long = InputReader.Position
        Dim ChunkSize As Integer = InputReader.ReadInt32

        Dim EventBytes As Byte() = InputReader.ReadBytes(ChunkSize)
        Dim EventsReader As New BigEndianBinaryReader(New MemoryStream(EventBytes))

        Dim PreviousStatusByte As Byte = 0

        Do
            Result.Add(MidiEvent.FromStream(EventsReader, ExceptionOffsetPosition, PreviousStatusByte))
        Loop Until TypeOf Result(Result.Count - 1) Is EndOfTrack

        For I As Integer = 1 To Result.Count - 1
            Result(I).TimeOffset += Result(I - 1).TimeOffset
        Next

        If Not EventsReader.EndOfStream Then _
            Throw New MidiFileFormatException(InputReader.Position, "Unexpected end-of-track event")

        Return Result

    End Function

End Class
